/**
 * Copyright: Copyright (c)2011
 * Company: 易宝支付(YeePay)
 */
package net.loyintean.pearlshell.base.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.loyintean.pearlshell.base.model.ILogInfo;
import net.loyintean.pearlshell.base.model.impl.LogInfoFactory;
import net.loyintean.pearlshell.base.service.HttpService;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

/**
 * 这个实现类是基于HttpClient-3.1编写的
 * 
 * @author：jun.lin@yeepay.com
 * @since：2015年2月6日 下午2:36:22
 * @version:
 */
@Deprecated
class HttpServiceImpl implements HttpService {

	private static final Logger LOGGER = Logger
			.getLogger(HttpServiceImpl.class);

	/**
	 * httpclient :创建客户端
	 * <p>
	 * 为它声明一个多线程的连接管理器，以保证多线程安全性
	 */
	private final HttpClient httpclient = new HttpClient(
			new MultiThreadedHttpConnectionManager());

	/**
	 * url :请求发送的路径
	 */
	private String url;

	/**
	 * 内部声明的一个枚举；用于枚举可用的http方法
	 * 
	 * @author：jun.lin@yeepay.com
	 * @since：2015年2月7日 下午10:28:49
	 * @version:
	 */
	private enum MethodEnum {
		POST, GET
	};

	/**
	 * method :方法类型；
	 * <p>
	 * post或get<br>
	 * 默认为post
	 */
	private MethodEnum method = MethodEnum.POST;

	/**
	 * contentType : 请求参数
	 * <p>
	 * 默认为“text/html;"
	 */
	private String contentType = "text/html;";

	/**
	 * charset :编码格式
	 * <p>
	 * 默认为UT-8
	 */
	private String charset = "UTF-8";

	/**
	 * connectionTimeout : 连接超时时间
	 * <p>
	 * 单位是毫秒，默认是3000ms=3s
	 */
	private int connectionTimeout = 3000;

	/**
	 * socketTimeout :socket读取时间
	 * <p>
	 * 单位是毫秒，默认是3000ms=3s
	 */
	private int socketTimeout = 3000;

	/**
	 * initialized : 是否已初始化标志位。true为已初始化；fasle为未初始化
	 */
	private boolean initialized = false;

	/**
	 * 初始化方法。为 {@link #httpclient}设定编码格式
	 * <p>
	 * 可以用spring来设定初始化方法
	 */
	private void init() {
		if (!initialized) {

			httpclient.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, charset);

			httpclient.getHttpConnectionManager().getParams()
					.setConnectionTimeout(connectionTimeout);

			httpclient.getHttpConnectionManager().getParams()
					.setSoTimeout(socketTimeout);

			initialized = true;
		}
	}

	/**
	 * @see com.yeepay.g3.core.onlinepayfee.utils.HttpService#send(java.lang.String)
	 */
	@Override
	public String send(String param) throws IOException {

		init();

		ILogInfo logInfo = LogInfoFactory.BUILD("service=" + toString()
				+ ",param=" + param);

		LOGGER.info(logInfo.start());

		// 创建调用方法
		HttpMethod method = generateMehtod(param, logInfo);

		// 执行方法
		int statusCode = httpclient.executeMethod(method);

		if (statusCode != HttpStatus.SC_OK) {
			LOGGER.error(logInfo.error("statusCode=" + statusCode));
			throw new IOException(logInfo.error("statusCode=" + statusCode));
		}

		// 获取返回结果
		String result = method.getResponseBodyAsString();

		method.releaseConnection();

		LOGGER.info(logInfo.end("result=" + result));

		return result;
	}

	/**
	 * 将参数写入http请求中
	 * <p>
	 * 如果是post方法，将参数写入请求body中<br>
	 * 如果是get方法，将参数后缀到url后。
	 * 
	 * @param param
	 * @return
	 * @throws UnsupportedEncodingException
	 *             使用post方法时，如果当前service设定的编码格式不合法，则抛出此异常
	 * @throws IllegalArgumentException
	 *             当前service的method不是合法的枚举值，则抛出此异常
	 */
	private HttpMethod generateMehtod(String param, ILogInfo logInfo)
			throws UnsupportedEncodingException {

		switch (method) {
		case POST:
			PostMethod postMethod = new PostMethod(url);

			postMethod.setRequestEntity(new StringRequestEntity(param,
					contentType + "; charset=" + charset, charset));

			return postMethod;

		case GET:
			GetMethod getMethod = new GetMethod(url);
			getMethod.setQueryString(param);
			return getMethod;

		default:
			throw new IllegalArgumentException("need POST or GET!");
		}

	}

	/**
	 * @param url
	 *            the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @param method
	 *            the method to set
	 */
	public void setMethod(String method) {
		this.method = MethodEnum.valueOf(method);
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("HttpServiceImpl [");
		if (url != null) {
			builder.append("url=");
			builder.append(url);
			builder.append(", ");
		}
		if (method != null) {
			builder.append("method=");
			builder.append(method);
		}
		builder.append("]");
		return builder.toString();
	}

	/**
	 * @param contentType
	 *            the contentType to set
	 */
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	/**
	 * @param charset
	 *            the charset to set
	 */
	public void setCharset(String charset) {
		this.charset = charset;
	}

	/**
	 * @param connectionTimeout
	 *            the connectionTimeout to set
	 */
	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	/**
	 * @param socketTimeout
	 *            the socketTimeout to set
	 */
	public void setSocketTimeout(int socketTimeout) {
		this.socketTimeout = socketTimeout;
	}

}
